﻿using System;
using System.Linq;
using System.Reflection;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using XWord.Common;
using XWord.Common.Attributes;
using XWord.ComponentBehaviors;


using uNhAddIns.ComponentBehaviors.Castle.Configuration;
using Microsoft.Practices.Composite.Modularity;

namespace XWord.GuyWire.Configurators
{
    public class ModelsConfigurator : IConfigurator
    {

        public void Configure(IWindsorContainer container)
        {
            var moduleCatalog = container.Resolve<IModuleCatalog>();
            foreach (var module in moduleCatalog.Modules)
            {
                var assembly = Assembly.Load(new AssemblyName(string.Format("{0}.Domain", module.ModuleName)));
                var modelServices = assembly.GetTypes()
                    .Where(t => t.GetCustomAttributes(typeof(IgnoreRegisterAttribute), true).Count() == 0)
                    .Where(t => t.IsInterface && t.Namespace.EndsWith("Model"));

                var modelImpl = Assembly.Load(new AssemblyName(string.Format("{0}.Domain.Impl", module.ModuleName))).GetTypes()
                    .Where(t => t.GetInterfaces().Any(i => modelServices.Contains(i)));

                foreach (Type service in modelServices)
                    foreach (Type impl in modelImpl)
                        if (service.IsAssignableFrom(impl))
                            container.Register(Component.For(service).ImplementedBy(impl).LifeStyle.Transient);
               
            }
        }
    }
}